import pandas as pd
import numpy as np
import requests
import time
from datetime import datetime


class USDT_CNY_Premium_Orderbook:
    def __init__(self):
        self.orderbook_data = pd.DataFrame()
        self.usdcnh_rate = None
        self.last_update = None

    def fetch_otc_data(self):
        """从币安API获取OTC商家数据"""
        url = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search"

        payload = {
            "page": 1,
            "rows": 20,
            "payTypes": [],
            "asset": "USDT",
            "tradeType": "BUY",  # 或 "SELL"
            "fiat": "CNY",
            "publisherType": None,
            "merchantCheck": False,
            "transAmount": ""
        }

        headers = {
            "Content-Type": "application/json"
        }

        try:
            response = requests.post(url, json=payload, headers=headers)
            data = response.json()
            return data['data']
        except Exception as e:
            print(f"Error fetching OTC data: {e}")
            return None

    def fetch_usdcnh_rate(self):
        """获取USD/CNH汇率"""
        # 这里可以使用多个数据源
        # 1. 外汇API
        # 2. 银行汇率
        # 3. 其他可靠数据源

        # 示例: 使用模拟数据
        return 7.25  # 假设当前USD/CNH汇率为7.25

    def calculate_premium(self, usdt_price, usdcnh_rate):
        """计算溢价率"""
        return (usdt_price / usdcnh_rate - 1) * 100

    def process_orderbook(self):
        """处理订单簿数据"""
        # 获取数据
        otc_data = self.fetch_otc_data()
        self.usdcnh_rate = self.fetch_usdcnh_rate()

        if not otc_data:
            return

        # 提取关键字段
        processed_data = []
        for adv in otc_data:
            advertiser = adv['advertiser']
            adv_detail = adv['adv']

            record = {
                'price': float(adv_detail['price']),
                'available': float(adv_detail['surplusAmount']),
                'min_amount': float(adv_detail['minSingleTransAmount']),
                'max_amount': float(adv_detail['maxSingleTransAmount']),
                'premium': self.calculate_premium(float(adv_detail['price']), self.usdcnh_rate),
                'completed_rate': float(advertiser['completedRate']),
                'completed_orders': int(advertiser['completedOrderQuantity']),
                'avg_completed_time': advertiser.get('avgCompletedTime', 0),
                'payment_methods': [method['identifier'] for method in adv_detail['tradeMethods']],
                'merchant_name': advertiser['nickName'],
                'merchant_id': advertiser['userNo'],
                'is_merchant': advertiser['userType'] == 'merchant',
                'timestamp': datetime.now().isoformat()
            }
            processed_data.append(record)

        # 创建DataFrame
        self.orderbook_data = pd.DataFrame(processed_data)

        # 按价格排序
        self.orderbook_data.sort_values('price', inplace=True)

        self.last_update = datetime.now()

    def get_best_offers(self, n=5):
        """获取最佳报价"""
        if self.orderbook_data.empty:
            return pd.DataFrame()

        return self.orderbook_data.head(n)

    def get_premium_summary(self):
        """获取溢价摘要统计"""
        if self.orderbook_data.empty:
            return {}

        return {
            'min_premium': self.orderbook_data['premium'].min(),
            'max_premium': self.orderbook_data['premium'].max(),
            'avg_premium': self.orderbook_data['premium'].mean(),
            'median_premium': self.orderbook_data['premium'].median(),
            'usdcnh_rate': self.usdcnh_rate,
            'update_time': self.last_update.isoformat()
        }

    def filter_by_criteria(self, min_completed_rate=90, max_premium=5, min_amount=100):
        """根据条件筛选订单"""
        if self.orderbook_data.empty:
            return pd.DataFrame()

        filtered = self.orderbook_data[
            (self.orderbook_data['completed_rate'] >= min_completed_rate) &
            (self.orderbook_data['premium'] <= max_premium) &
            (self.orderbook_data['max_amount'] >= min_amount)
            ]

        return filtered.sort_values('premium')


# 使用示例
if __name__ == "__main__":
    orderbook = USDT_CNY_Premium_Orderbook()
    orderbook.process_orderbook()

    # 获取最佳报价
    best_offers = orderbook.get_best_offers(10)
    print("最佳报价:")
    print(best_offers[['price', 'premium', 'available', 'completed_rate']])

    # 获取溢价摘要
    summary = orderbook.get_premium_summary()
    print(f"\n溢价摘要:")
    print(f"USD/CNH汇率: {summary['usdcnh_rate']}")
    print(f"最低溢价: {summary['min_premium']:.2f}%")
    print(f"最高溢价: {summary['max_premium']:.2f}%")
    print(f"平均溢价: {summary['avg_premium']:.2f}%")

    # 根据条件筛选
    filtered = orderbook.filter_by_criteria(min_completed_rate=95, max_premium=2, min_amount=1000)
    print(f"\n符合条件的订单({len(filtered)}个):")
    print(filtered[['price', 'premium', 'available', 'completed_rate']])